package com.xuecheng.order.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.xuecheng.api.order.OrderApi;
import com.xuecheng.api.order.model.OrdersDTO;
import com.xuecheng.api.order.model.pay.PayCodeUrlResult;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单服务Controller
 */
@Slf4j
@RestController
public class OrdersController implements OrderApi {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayService payService;

    /**
     * 创建订单
     *
     * @param coursePubId 课程发布ID
     * @return 订单传输对象封装
     */
    @GetMapping("orders/create/{coursePubId}")
    public OrdersDTO createOrder(@PathVariable Long coursePubId) {
        return null;
    }

    /**
     * 创建订单支付数据
     *
     * @param orderNo
     * @return
     */
    @GetMapping("orderPay/wxPay/createPay")
    public PayCodeUrlResult createPayment(String orderNo) {
        return null;
    }

    /**
     * 订单支付通知，wx支付平台来调用此方法
     *
     * @param request
     * @return
     */
    @RequestMapping("order-pay/wx-pay/notify-result")
    public String notifyPayment(HttpServletRequest request) {
        log.info("订单支付通知方法开始执行");
        try {
            // 从数据流中获取微信返回的支付结果通知（xml结构）
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            payService.notifyPayment(xmlResult);
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常 => {}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
}
